<template>
  <div>
    <!-- 图片上传组件辅助 -->
    <el-upload
      class="avatar-uploader quill-img"
      :action="uploadImgUrl"
      name="file"
      :headers="headers"
      :show-file-list="false"
      :on-success="quillImgSuccess"
      :on-error="uploadError"
      :before-upload="quillImgBefore"
      accept='.jpg,.jpeg,.png,.gif'
    ></el-upload>

    <el-upload
      class="avatar-uploader quill-video"
      ref="upload"
      :action="uploadFileUrl"
      :headers="headers"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :on-success="quillVideoSuccess"
      :on-error="uploadError"
      :before-upload="quillVideoBefore"
      accept='.mp4'
      >
    </el-upload>

    <!--videoUploadTag 默认是 false -->
    <!--所以这里的上传弹框是隐藏的 -->
    <!--当点击编辑器菜单栏中的视频图标时，将videoUploadTag 修改为 true 在页面上显示出来插入视频的弹框-->
    <div :visible.sync="videoUploadTag">
      <el-dialog
        width="50%"
        id="video_upload"
        style="margin-top: 1px"
        title="视频上传"
        :visible.sync="videoUploadTag"
        append-to-body>
        <el-tabs v-model="activeName" @tab-click="videoSelectTagClick" value="0">
          <el-tab-pane label="新增视频链接" name="first">
            <el-input v-model="videoPath" placeholder="请输入视频链接" clearable></el-input>
            <el-button type="primary" size="small" style="margin: 20px 0px 0px 0px " @click="addVideoLink()">新增
            </el-button>
          </el-tab-pane>
          <el-tab-pane label="本地上传" name="second">
            <!--<el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadFileUrl"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :on-success="quillVideoSuccess"
              :on-error="uploadError"
              :before-upload="quillVideoBefore"
              accept='.mp4,.flv,.mkv,.avi,.rmvb'
              :auto-upload="false">
              <el-button slot="trigger"  style="background-color: #13ce66;height: 33px;padding: 0;width: 104px" type="success">选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
              <div slot="tip" class="el-upload__tip">只能上传mp4/flv/mkv/avi/rmvb文件</div>
            </el-upload>-->

            <el-button style="margin-left: 10px;" size="small" type="primary" @click="chooseVideoFile">选择文件</el-button>
            <div class="el-upload__tip">只能上传mp4文件</div>
          </el-tab-pane>

        </el-tabs>
      </el-dialog>
    </div>

    <!-- 富文本组件 -->
    <quill-editor
      class="editor"
      v-model="content"
      :ref="editorRef"
      :id="editorRef"
      :options="editorOption"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @change="onEditorChange($event)"
    ></quill-editor>
  </div>
</template>

<script>
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"],       // 加粗 斜体 下划线 删除线
  ["blockquote", "code-block"],                    // 引用  代码块
  [{ list: "ordered" }, { list: "bullet" }],       // 有序、无序列表
  [{ indent: "-1" }, { indent: "+1" }],            // 缩进
  [{ size: ["small", false, "large", "huge"] }],   // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }],         // 标题
  [{ color: [] }, { background: [] }],             // 字体颜色、字体背景颜色
  [{ align: [] }],                                 // 对齐方式
  ["clean"],                                       // 清除文本格式
  ["link", "image", "video"]                       // 链接、图片、视频
];
import { getToken } from '@/utils/auth'
import Quill from 'quill'
import Video from './quill/video'
import Image from './quill/image'

import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import defaultSetting from "@/settings";
import $ from 'jquery';

//quill编辑器的字体
var fonts = ['SimSun', 'SimHei','Microsoft-YaHei','KaiTi','FangSong','Arial','Times-New-Roman','sans-serif'];
var Font = Quill.import('formats/font');
Font.whitelist = fonts; //将字体加入到白名单
Quill.register(Font, true);

Quill.register(Video, true)
Quill.register(Image, true)

export default {
  props: {
    /* 编辑器的内容 */
    value: {
      type: String
    },
    /* 图片大小 */
    maxSize: {
      type: Number,
      default: 4000 //kb
    },
    editorRef: {
      type: String,
      default: 'quillEditor'
    }
  },
  components: { quillEditor },
  data() {
    let that = this;
    return {
      fileList: [],
      videoUploadTag: false,
      activeName: "first",
      content: this.value,
      picturePath: "",
      videoPath: "",
      // uploadImgUrl: "",
      editorOption: {
        theme: "snow", // or 'bubble'
        placeholder: "请输入内容",
        modules: {
          toolbar: {
            container:
              [
              ["bold", "italic", "underline", "strike"],       // 加粗 斜体 下划线 删除线
              ["blockquote", "code-block"],                    // 引用  代码块
              [{ list: "ordered" }, { list: "bullet" }],       // 有序、无序列表
              [{ indent: "-1" }, { indent: "+1" }],            // 缩进
              [{ size: ["small", false, "large", "huge"] }],   // 字体大小
              [{ header: [1, 2, 3, 4, 5, 6, false] }],         // 标题
              [{ color: [] }, { background: [] }],             // 字体颜色、字体背景颜色
              [{ 'font': fonts }],
              [{ align: [] }],                                 // 对齐方式
              ["clean"],                                       // 清除文本格式
              ["link", "image", "video"]                       // 链接、图片、视频
            ],
            handlers: {
              image: function(value) {
                if (value) {
                  // 触发input框选择图片文件
                  //document.querySelector(".quill-img input").click();
                  let parentEle = this.container.parentNode.parentNode;
                  parentEle.querySelector('.quill-img input').click();
                } else {
                  this.quill.format("image", false);
                }
              },
              video: function(value) {
                if (value) {
                  that.videoUploadTag = true;
                  // 触发input框选择文件
                 /* document.querySelector(".quill-video input").click();
                } else {
                  this.quill.format("video", false);*/
                }
              }
            }
          }
        }
      },
      // uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/fdfs/uploadImageAndCrtThumbImageWithManage', // 上传的图片服务器地址
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/fdfs/uploadWithManage', // 上传的文件服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    };
  },
  watch: {
    value: function() {
      this.content = this.value;
    }
  },
  methods: {
    onEditorBlur() {
      //失去焦点事件
    },
    onEditorFocus() {
      //获得焦点事件
    },
    onEditorChange() {
      //内容改变事件
      this.$emit("input", this.content);
    },
    videoSelectTagClick(){},
    chooseVideoFile(){
      let parentEle = document.querySelector('#'+this.editorRef).parentNode;
      parentEle.querySelector(".quill-video input").click();
      this.videoUploadTag = false;
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {},
    handlePreview(file) {},
    // 富文本图片上传前
    quillImgBefore(file) {
      let fileType = file.type;
			if(fileType === 'image/jpeg' || fileType === 'image/png'){
				return true;
			}else {
				this.$message.error('请插入图片类型文件(jpg/jpeg/png)');
				return false;
			}
    },
    quillImgSuccess(res, file) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      let quill = this.$refs[this.editorRef].quill;
      let selection = quill.getSelection();
      // 如果上传成功
      if (res.code == 200) {
        // 获取光标所在位置
        // let length = quill.getSelection().index;

        //当编辑器中没有输入文本时，这里获取到的 range 为 null
        let range = quill.selection.savedRange;
        //视频插入在富文本中的位置
        let index = 0;
        if (range == null) {
          index = 0;
        } else {
          index = range.index;
        }

        // 插入图片  res.url为服务器返回的图片地址，默认使用缩略图
        // let index = res.url.indexOf('.');
        //缩略图
        // let url = defaultSetting.picturePath + res.url.slice(0, index) + defaultSetting.pictureThumbSuffix + res.url.slice(index);
        //原图
        let url = defaultSetting.picturePath + res.url;
        quill.insertEmbed(index, "image", url);
        // 调整光标到最后
        quill.setSelection(index + 1);

        if(this.picturePath && this.picturePath.length > 0) {
          this.picturePath += "," + res.url;
        }else{
          this.picturePath = res.url;
        }
      } else {
        this.$message.error("图片插入失败");
      }
    },
    // 富文本图片上传前
    quillVideoBefore(file) {
      let fileType = file.type;
      // if(fileType === 'video/mp4' || fileType === 'video/x-flv' || fileType === 'video/x-matroska' || fileType === 'video/avi' || fileType === 'video/rmvb'){
      if(fileType === 'video/mp4'){
        return true;
      }else {
        this.$message.error('请插入mp4类型视频文件');
        return false;
      }
    },

    quillVideoSuccess(res, file) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      // this.videoUploadTag = false;
      let quill = this.$refs[this.editorRef].quill;
      // 如果上传成功
      if (res.code == 200) {
        //当编辑器中没有输入文本时，这里获取到的 range 为 null
        let range = quill.selection.savedRange;
        //视频插入在富文本中的位置
        let index = 0;
        if (range == null) {
          index = 0;
        } else {
          index = range.index;
        }
        //视频地址
        let url = defaultSetting.picturePath + res.url;
        quill.insertEmbed(index, "video", url);
        // 调整光标到最后
        quill.setSelection(index + 1);

        if(this.picturePath && this.picturePath.length > 0) {
          this.picturePath += "," + res.url;
        }else{
          this.picturePath = res.url;
        }
      } else {
        this.$message.error("视频插入失败");
      }
    },
    // 富文本图片上传失败
    uploadError() {
      // loading动画消失
      this.$message.error("插入失败");
    },

    addVideoLink() {
      if (this.videoPath.length == 0) {
        this.$message.error('请输入视频链接');
      }
      //当编辑器中没有输入文本时，这里获取到的 range 为 null
      // let range = this.$refs.quillEditor.quill.getSelection();
      let range = this.$refs[this.editorRef].quill.selection.savedRange;
      //视频插入在富文本中的位置
      let index = 0;
      if (range == null) {
        index = 0;
      } else {
        index = range.index;
      }
      //隐藏弹框
      this.videoUploadTag = false;
      //将视频链接插入到当前的富文本当中
      this.$refs[this.editorRef].quill.insertEmbed(index, 'video', this.videoPath);
    },
  }
};
</script>

<style>
.editor {
  line-height: normal !important;
  /*height: 350px;*/
}
.ql-editor{
  height: 350px;
}
.quill-img {
  display: none;
}
.quill-video {
  display: none;
}
.ql-video {
  /*width: 360px;*/
  width: 100%;
}
.ql-snow .ql-tooltip[data-mode="link"]::before {
  content: "请输入链接地址:";
}
.ql-snow .ql-tooltip::before {
  content: "链接地址:";
}
.ql-snow .ql-tooltip a.ql-action::after{
  content: "编辑";
}
.ql-snow .ql-tooltip a.ql-remove::before{
  content: "删除";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0px;
  content: "保存";
  padding-right: 0px;
}

.ql-snow .ql-tooltip[data-mode="video"]::before {
  content: "请输入视频地址:";
}

.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: "14px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
  content: "10px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
  content: "18px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
  content: "32px";
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: "文本";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: "标题1";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: "标题2";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: "标题3";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: "标题4";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: "标题5";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: "标题6";
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: "标准字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
  content: "衬线字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
  content: "等宽字体";
}
</style>
